from django.shortcuts import render, redirect
from django.http import HttpResponse
from ..models import Department, UserInfo, PrettyNum
from django import forms
from django.forms import Form, ModelForm
from django.utils.safestring import mark_safe
from ..utils.pagination import Pagination
from ..utils.bootstrap import BootStrapModelForm
from ..utils.form import UserModelForm, PrettynumModelForm, PrettynumEditModelForm
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

def prettynum_list(request):
    # 靓号搜索功能
    data_dict = {}
    value = request.GET.get('q')
    if value:
        data_dict = {'mobile__contains': value}
    # 加上第二排序id字段，分页的sql语句使用offset偏移量，会造成到第20条记录的两个分页出bug
    data_list = PrettyNum.objects.all().filter(**data_dict).order_by("level", "id")
    page_object = Pagination(request, data_list)
    page_string = page_object.html()
    context = {"data_list": page_object.page_queryset, "search_data": data_dict, "page_string": page_string}
    return render(request, 'prettynum_list.html', context)

def prettynum_add(request):
    if request.method == 'GET':
        form = PrettynumModelForm()
        return render(request, 'prettynum_add.html', {'form': form})
    form = PrettynumModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/prettynum/list/')
    return render(request, 'prettynum_add.html', {'form': form})

def prettynum_edit(request, nid):
    if request.method == 'GET':
        row_object = PrettyNum.objects.filter(id=nid).first()
        form = PrettynumEditModelForm(instance=row_object)
        return render(request, 'prettynum_edit.html', {'form': form})
    row_object = PrettyNum.objects.filter(id=nid).first()
    form = PrettynumEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/prettynum/list/')
    return render(request, 'prettynum_edit.html', {'form': form})

def prettynum_delete(request, nid):
    PrettyNum.objects.filter(id=nid).delete()
    return redirect('/prettynum/list/')
